package com.samoiloff.ui.btns {
	import flash.display.MovieClip;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;

	/**
	 * @author Alexander Slavshik <as.kvint@gmail.com>
	 * created 18.03.2010
	 */
	public class ResizableButton extends EventDispatcher {
		private var _mc:MovieClip;
		private var _leftCorner:MovieClip;
		private var _rightCorner:MovieClip;
		private var _middle:MovieClip;
		private var _width:Number;
		private var _hitArea:MovieClip;

		public function ResizableButton(mc:MovieClip) {
			_mc = mc;
			
			_leftCorner = _mc.leftMc;			_rightCorner = _mc.rightMc;			_middle = _mc.middleMc;
			_hitArea = _mc.hitAreaMc;
			
			state = 1;
			
			_mc.addEventListener(MouseEvent.ROLL_OVER, mouseHandler);
			_mc.addEventListener(MouseEvent.ROLL_OUT, mouseHandler);
			_mc.addEventListener(MouseEvent.MOUSE_DOWN, mouseHandler);
			_mc.addEventListener(MouseEvent.MOUSE_UP, mouseHandler);
			_mc.addEventListener(MouseEvent.CLICK, mouseHandler);
		}

		private function mouseHandler(event:MouseEvent):void {
			switch(event.type) {
				case MouseEvent.ROLL_OVER:
					state = 2;
					break;
				case MouseEvent.MOUSE_DOWN:
					state = 3;
					break;
				case MouseEvent.CLICK:
					dispatchEvent(event);
				case MouseEvent.ROLL_OUT:
				case MouseEvent.MOUSE_UP:
					state = 1;
					break;
				default:
			}
		}

		public function destroy():void {
			_hitArea.removeEventListener(MouseEvent.ROLL_OVER, mouseHandler);
			_hitArea.removeEventListener(MouseEvent.MOUSE_DOWN, mouseHandler);
			_hitArea.removeEventListener(MouseEvent.MOUSE_UP, mouseHandler);
			_hitArea.removeEventListener(MouseEvent.ROLL_OUT, mouseHandler);
			_hitArea.removeEventListener(MouseEvent.CLICK, mouseHandler);
		}

		public function get width():Number {
			return _width;
		}

		public function set width(width:Number):void {
			_width = width;
			_middle.width = _width - _leftCorner.width - _rightCorner.width;
			_rightCorner.x = _width; 
		}

		private function set state(state:int):void {
			_middle.gotoAndStop(state);
			_leftCorner.gotoAndStop(state);
			_rightCorner.gotoAndStop(state);
		}
	}
}
